package cn.schoolwow.flow.monitor.module.business.scheduleJob.definition.flow.business;

import cn.schoolwow.ams.module.block.listBlock.common.domain.operation.ListBlockRequest;
import cn.schoolwow.flow.monitor.domain.FlowMonitorOption;
import cn.schoolwow.flow.monitor.entity.ScheduleJob;
import cn.schoolwow.flow.monitor.module.business.scheduleJob.definition.domain.ScheduleJobContext;
import cn.schoolwow.quickdao.domain.database.dml.UpdateType;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.instanceList.QueryInstanceList;
import com.alibaba.fastjson.JSONArray;
import org.springframework.context.ApplicationContext;

import java.util.List;

public class CancelScheduleJobFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        flowContext.executeFlowList(new GetScheduleJobContextListFlow());
        List<ScheduleJobContext> list = flowContext.getData("list", List.class);
        if(null==list||list.isEmpty()){
            throw new IllegalArgumentException("当前定时任务流程列表为空");
        }
        ApplicationContext applicationContext = flowContext.checkInstanceData(ApplicationContext.class);
        FlowMonitorOption flowMonitorOption = applicationContext.getBean(FlowMonitorOption.class);

        ListBlockRequest listBlockRequest = flowContext.checkInstanceData(ListBlockRequest.class);
        boolean mayInterruptIfRunning = flowContext.checkData("mayInterruptIfRunning",boolean.class);

        JSONArray array = new JSONArray();
        if(null!=listBlockRequest.array){
            array.addAll(listBlockRequest.array);
        }else{
            array.add(listBlockRequest.row);
        }
        List<ScheduleJob> scheduleJobList = array.toJavaList(ScheduleJob.class);
        for(ScheduleJob scheduleJob:scheduleJobList){
            ScheduleJobContext scheduleJobContext = QueryInstanceList.newQuery(list)
                    .addQuery("categoryName", scheduleJob.getCategoryName())
                    .addQuery("name", scheduleJob.getName())
                    .execute()
                    .getOne();
            if(null==scheduleJobContext){
                throw new IllegalArgumentException("定时任务流程不存在!分类:"+scheduleJob.getCategoryName()+",名称:"+scheduleJob.getName());
            }
            if(null==scheduleJobContext.scheduledFuture){
                throw new IllegalArgumentException("定时任务流程不存在未运行!");
            }
            boolean cancel = scheduleJobContext.scheduledFuture.cancel(mayInterruptIfRunning);
            if(!cancel){
                throw new IllegalArgumentException("取消定时任务失败!");
            }
            flowMonitorOption.dao.partColumn("enable").updateType(UpdateType.UpdateByUniqueKey).update(scheduleJob);
        }
    }

    @Override
    public String name() {
        return "取消定时任务运行";
    }

}
